#include "documentloader.h"
#include <QFile>
#include "../document.h"
#include "../gameobjects/graphicsobject.h"
#include "../gameobjects/animation.h"
#include "../gameobjects/texture.h"
#include "../physics/collisionshapes.h"

DocumentLoader::DocumentLoader(QObject *parent) :
    DocumentSerializer(parent)
{
}

void DocumentLoader::loadGraphicsObject(QDataStream &in)
{
    int guid = 0;
    QString id;

    in >> guid;
    in >> id;

    QPointer<GraphicsObject> gobject = m_doc->createGraphicsObject(id);

    bool hasAnimations, hasTextures;

    in >> hasAnimations;

    if(!hasAnimations)
    {
        in >> hasTextures;

        if(!hasTextures)
        {
            return;
        }

        loadTexture(qobject_cast<AbstractObject*>(gobject), in);

        int numColShapes = 0;
        in >> numColShapes;

        if(numColShapes > 0)
        {
            for(int i=0;i<numColShapes;++i)
            {
                loadCollisionShape(gobject->collisionShapes(), in);
            }
        }
    }
}

void DocumentLoader::loadTexture(QPointer<AbstractObject> parent, QDataStream &in)
{
    int nGuid, nParentGuid;
    QString strID, strFileName;

    in >> nGuid;
    in >> strID;
    in >> (int)nParentGuid;
    in >> strFileName;

    m_doc->createTexture(strID, parent, strFileName);
}

void DocumentLoader::loadCollisionShape(QList<QPointer<CollisionShape> > &cShapes, QDataStream &in)
{
    int ownerGuid = -1;

    in >> ownerGuid;

    int type = -1;
    in >> type;

    QRectF rect;
    QPointF center;
    float radius;
    QPolygonF poly;

    switch(type)
    {
        case 0: in >> rect;
                cShapes << m_doc->createRectShape(rect);
                break;
        case 1: in >> center;
                in >> radius;
                cShapes << m_doc->createCircleShape(center, radius);
                break;
        case 2: in >> poly;
                cShapes << m_doc->createPolyShape(poly);
                break;
    }
}

bool DocumentLoader::serialize(const QString &filePath, QPointer<Document> document)
{
    m_doc = document;

    QFile file(filePath);

    if(!file.open(QIODevice::ReadOnly))
    {
        return false;
    }

    QDataStream in(&file);

    int goCount = 0;
    in >> goCount;

    if(goCount > 0)
    {
        for(int i=0; i < goCount;i++)
        {
            loadGraphicsObject(in);
        }
    }

    file.close();
    return true;
}
